# fiery_flask_权限管理实例
from flask import Flask, current_app, jsonify, g, request
from flask_httpauth import HTTPTokenAuth
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer



app = Flask(__name__)
auth = HTTPTokenAuth(scheme='Token')
app.config['SECRET_KEY'] = 'weex'


#用户数据
tokens = {
    1: {'uid': 1, 'name': 'fiery', 'sex': 'm', 'age': 22, 'per': 'admin'},
    2: {'uid': 2, 'name': 'fiery2', 'sex': 'm', 'age': 222, 'per': 'admin2'},
}

#权限数据
url_admin = {
    'admin': ['/']
}

#生成Token
def genrate_outh_toekn(uid):
    s = Serializer(current_app.config['SECRET_KEY'])
    return s.dumps(tokens[uid])

@app.route('/gettoken/<int:userid>', methods = ['GET'])
def get_token(userid: int) -> request:
    token = genrate_outh_toekn(userid)
    data = {
        'token': token.decode('ascii')
    }
    return jsonify(data), 201


#校验token
# @auth.verify_token
# def verify_token(token):
#     if token in tokens:
#         g.current_user = tokens[token]
#         return True
#     return False

@auth.verify_token
def verify_token(token):
    s = Serializer(current_app.config['SECRET_KEY'])
    data = s.loads(token)
    print(data['per'])
    print(url_admin[data['per']])
    print(str(request.url_rule))
    #判断是否有访问的url权限
    if str(request.url_rule) in url_admin[data['per']]:
        g.data = data
        return True
    else:
        return False


@app.route('/')
@auth.login_required
def index():
    return "Hello, {}".format(g.data)

if __name__ == '__main__':
    app.run()



#Authorization Token secret-token-1